#! /usr/bin/python

import argparse
import os
import json

ohos_path = r"."
output_path = r"."

def get_subsystem():
    subsystem_json_path = os.path.join(ohos_path, r"build/subsystem_config.json")
    subsystem_item = {}
    with open(subsystem_json_path, 'rb') as f:
        subsystem_json = json.load(f)
        # get sunsystems
        for i in subsystem_json:
            subsystem_name = subsystem_json[i]["name"]
            subsystem_path = os.path.join(ohos_path, subsystem_json[i]["path"])
            if not os.path.exists(subsystem_path):
                continue
            cmd = 'find ' + subsystem_path + ' -name bundle.json'
            re = os.popen(cmd).readlines()
            # get components
            component_list = []
            for j in re:
                with open(j.strip('\n'), 'rb') as bundle:
                    bundle_json = json.load(bundle)
                    component_item = {}
                    if 'segment' in bundle_json and 'destPath' in bundle_json["segment"]:
                        component_item[bundle_json["component"]["name"]] = bundle_json["segment"]["destPath"]
                    else:
                        temp_path = j.strip('\n')
                        component_item[bundle_json["component"]["name"]] = "Unknow. Please check " + temp_path
                    component_list.append(component_item)
            subsystem_item[subsystem_name] = component_list
    # output to json
    subsystem_item_json = json.dumps(subsystem_item, indent=4, separators=(', ', ': '))
    out_path = os.path.abspath(os.path.normpath(output_path)) + '/subsystem_component_path.json'
    with open(out_path, 'w') as out_file:
        out_file.write(subsystem_item_json)
    print("Output path: " + out_path)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("project", help="project root path.", type=str)
    parser.add_argument("-o", "--outpath", help="specify an output path.", type=str)
    args = parser.parse_args()
    global ohos_path
    ohos_path = os.path.abspath(args.project)
    if not is_project(ohos_path):
        print("'" + ohos_path + "' is not a valid project path.")
        exit(1)
    global output_path
    if args.outpath:
        output_path = args.outpath
    
def is_project(path) -> bool:
    p = os.path.normpath(path)
    return os.path.exists(p + '/.repo/manifests')

if __name__ == '__main__':
    parse_args()
    get_subsystem()